<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

use Auth;
use Hash;
use Cache;

use App\Models\Setting;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    static function adminGuard()
    {
        return Auth::guard('admin');
    }

    static function getHash($value)
    {
        return Hash::make($value);
    }

    static function code($code, $message='ok', $name='message')
    {
        return response()->json([
            'code' => $code,
            $name => $message,
        ]);
    }

    static function getPages($data)
    {
        return [
            'page' => $data['current_page'],
            'total' => $data['total'],
            'page_size' => $data['per_page'],
        ];
    }

    static function typeToId($type)
    {
        $datas = [
            // 图片
            'banner' => 101,
            'honor' => 102,

            // 文章
            'news' => 201,
            'notice' => 202,
            'activity' => 203,
            'attract' => 204,
            'culture' => 205,
            'consultation' => 206,
            'service' => 207,
            'investment' => 208,
            'policy' => 209,
        ];

        if (is_int($type)) {
            return array_search($type, $datas);
        }

        return isset($datas[$type]) ? $datas[$type] : 0;
    }

    static function getSetting($name, $value=null)
    {
        if ($name == 'forget') {
            Cache::forget('setting');
            return;
        }

        $data = Cache::rememberForever('setting', function () {
            $datas = [];
            
            foreach (Setting::all() as $value) {
                $datas[$value['name']] = $value['value'];
            }

            return $datas;
        });

        if (!$value) {
            return isset($data[$name]) ? $data[$name] : null;
        } else {
            return isset($data[$name][$value]) ? $data[$name][$value] : null;
        }
    }

    static function saveSetting($name, $data)
    {
        Setting::updateOrCreate(
            ['name' => $name],
            ['value' => $data]
        );

        self::getSetting('forget');
    }
}
